/*
 * import {loadCityLib}  from '../lib/kairCity';
 * loadCityLib({prnTid: '#city', tag: '.from', from: fromTagVal, to: toTagVal});
 * prnTid 父元素
 * tag 点击的当前元素：目的地或者出发地
 * from 出发地的值
 * to 目的地的值
 * */

import cfg from '../config';
import {setCache, getCache, removeCache}  from '../lib/kcache';
import * as ajax  from '../lib/kajax';
import {Slider, sliderHide, sliderShow} from "../lib/kslider";

const $ = require('../lib/kdom');
const keyArr = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"];

function cityDataCache(val) {
  if (val !== undefined) {
    setCache(cfg.air.airCityLib, {data: val, date: new Date(), expire: cfg.app.expire});
  } else {
    return getCache(cfg.air.airCityLib) || '';
  }
}

function loadAirCityLib(options) {
  let rc = cityDataCache();
  if (rc) {
    initCity(rc, options);
    // console.log('本地存储', rc);
  } else {
    ajax.get(`${cfg.air.host}${cfg.air.cityLib}`, '', (rs) => {
      if (rs) {
        let rc = eval('(' + rs + ')');
        cityDataCache(rc);
        initCity(rc, options);
        // console.log('rc', rc);
      }
    });
  }
}

function initCity(data, options) {
  let rc = `<header class="bar bar-nav thame-danger"><div class="icon icon-left pull-left" id="cityClose"></div><h1 class="title">选择城市</h1></header>
            <div class="hotkey">
                <div id="hotkey" class="hotkey-item">
                    ${getHotKey()}
                </div>
            </div>
            <div class="content">
                <div class="city-container" id="cityContainer">
                    <h4 class="city-title">热门城市</h4>
                    ${createCity(data, options)}
                </div>
            </div>`;
  // console.log(rc);
  new Slider({content: rc});
  cityClose.onclick = () => {
    sliderHide();
  };
}

function getHotKey() {
  let rc = '';
  for (let i = 0, len = keyArr.length; i < len; i++) {
    rc += `<a href="#jump-${keyArr[i].toLowerCase()}">${keyArr[i]}</a>`;
  }
  return rc;
}

function createCity(data, opt) {
  let rc = '';
  let hotCity = '';//第一次循环筛选出热门城市
  let allCity = '';//全部的城市
  if (data) {
    let bindClick = null;
    let className = '';

    for (let i = 0, d = keyArr, keyLen = d.length; i < keyLen; i++) {
      hotCity = allCity = '';
      //获得城市
      for (let j = 0, o = data, len = o.length; j < len; j++) {
        /*判断已选中的城市*/
        if (opt.from == o[j]['info'] || opt.to == o[j]['info']) {
          className = 'active';
          bindClick = '';
        } else {
          className = '';
          bindClick = `onclick=selectCity(this,${JSON.stringify(o[j])},${JSON.stringify(opt)})`;
        }
        /*区分热门城市*/
        if (parseInt(o[j]['isHot']) === 1) {
          hotCity += `<a class="city-item ${className}" ${bindClick}>${o[j]['info']}</a>`;
        }
        /*全部城市*/
        if (o[j]['value'].indexOf(d[i]) === 0 && parseInt(o[j]['isHot']) !== 1) {
          allCity += `<a class="city-item ${className}" ${bindClick}>${o[j]['info']}</a>`;
        }
      }
      // 排序 A、B、C、...
      if (i < keyLen) {
        if (allCity) {
          rc += `<h4 class="city-title" id="jump-${d[i].toLowerCase()}">${d[i]}</h4>`;
        }
      }
      rc += allCity;
      /*j*/
    }
    /*i*/
    rc = hotCity + rc;
  }
  return rc;
}

window.selectCity = (that, data, opt) => {
  let val = data.info;
  let tag = null;
  if (opt.prnTid)
    tag = $.qu(`${opt.prnTid} ${opt.tag}`);
  else
    tag = $.qu(opt.tag);
  if (tag) $.html(tag, val);
  sliderHide();
};

export {loadAirCityLib}
